<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图 -->
    <el-card>
      <el-alert
        title="警告提示的文案"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <el-row>
        <el-col>
          <!-- 级联选择器 -->
          <span>选择商品分类:</span>
          <el-cascader
            clearable
            v-model="selectedCateKeys"
            :options="cateList"
            :props="{
              expandTrigger: 'hover',
              value: 'cat_id',
              label: 'cat_name',
              children: 'children',
            }"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            @click="addDialogVisible = true"
            type="primary"
            sizi="mini"
            :disabled="isBtnDisabled"
            >添加参数</el-button
          >
          <!-- 动态表格 -->
          <el-table :data="manyTableData" stripe border>
            <!-- 展开项 -->
            <!-- 循环渲染标签 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i,scope.row)">{{ item }}</el-tag
                >
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button type="warning" @click="deleteData(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            @click="addDialogVisible = true"
            type="primary"
            sizi="mini"
            :disabled="isBtnDisabled"
            >添加属性</el-button
          >
          <!-- 静态表格 -->
          <el-table :data="onlyTableData" stripe border>
             <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i,scope.row)">{{ item }}</el-tag
                >
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button type="warning" @click="deleteData(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addFrom"
        :rules="rules"
        ref="addFromRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addFrom.attr_name"></el-input> </el-form-item
      ></el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addPrame">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editFrom"
        :rules="rules"
        ref="editFromRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editFrom.attr_name"></el-input> </el-form-item
      ></el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editPrame">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
/*eslint-disable*/

export default {
  data() {
    return {
      editDialogVisible: false,
      // 编辑表单数据

      editFrom: {
        attr_name: "",
      },
      //   表单验证规则

      rules: {
        attr_name: [{ required: true, message: "请输入内容", trigger: "blur" }],
      },
      // 表单数据
      addFrom: {
        attr_name: "",
      },
      // 控制对话框
      addDialogVisible: false,
      manyTableData: [],
      onlyTableData: [],
      cateList: [],
      activeName: "many",
      // 级联选择框双向绑定到的数组
      selectedCateKeys: [],
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("/categories");
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品分类失败");
      }
      this.cateList = res.data;
      console.log(res);
    },
    // 级联选择器发生变化触发
    async handleChange() {
      this.getParamsData();
    },
    async getParamsData() {
      // 判断是不是选中三级分类
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = [];
        this.manyTableData=[]
        this.onlyTableData=[]
        return;
      }

      const { data: res } = await this.$http.get(
        `/categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } }
      );
      if (res.meta.status !== 200) {
        return;
      }
      res.data.forEach((i) => {
        // 字符串分割，变成数组
        i.attr_vals = i.attr_vals ? i.attr_vals.split(" ") : [];
        // 控制文本框的显示
        i.inputVisible = false;
        i.inputValue = "";
        console.log(i.attr_vals);
      });

      if (this.activeName === "many") {
        this.manyTableData = res.data;
      } else {
        this.onlyTableData = res.data;
      }
      console.log(res);
    },
    // tabs 点击事件
    handleClick() {
      this.getParamsData();

      console.log(this.activeName);
    },
    // 监听对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFromRef.resetFields();
    },
    // 确定/提交点击事件
    addPrame() {
      this.$refs.addFromRef.validate(async (valid) => {
        if (!valid) {
          return;
        }
        const { data: res } = await this.$http.post(
          `/categories/${this.cateId}/attributes`,
          { attr_name: this.addFrom.attr_name, attr_sel: this.activeName }
        );
        if (res.meta.status !== 201) {
          return this.$message.error("提交数据失败");
        }
        this.$message.success("提交数据成功");
        this.addDialogVisible = false;
        this.getParamsData();
      });
    },
    // 编辑对话框
    async showEditDialog(attr_id) {
      const { data: res } = await this.$http.get(
        `/categories/${this.cateId}/attributes/${attr_id}`,
        { params: { attr_sel: this.activeName } }
      );

      if (res.meta.status !== 200) {
        return this.$message.error("获取编辑对话框数据失败");
      }
      this.editFrom = res.data;
      this.editDialogVisible = true;
    },
    // 编辑对话框关闭监听
    editDialogClosed() {
      // 重置表单
      this.$refs.editFromRef.resetFields();
    },
    // 点击修改的确定按钮
    editPrame() {
      this.$refs.editFromRef.validate(async (v) => {
        if (!v) {
          return;
        }
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editFrom.attr_id}`,
          { attr_name: this.editFrom.attr_name, attr_sel: this.activeName }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("更新失败");
        }
        this.getParamsData();
        this.editDialogVisible = false;
        this.$message.success("更新成功");
      });
    },
    // 根据id删除数据
    async deleteData(attr_id) {
      const deletebtn = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => {
        return err;
      });
      if (deletebtn !== "confirm") {
        return;
      } else {
        const { data: res } = await this.$http.delete(
          `/categories/${this.cateId}/attributes/${attr_id}`
        );
        if (res.meta.status !== 200) {
          return this.$message.error("删除失败");
        }
        this.getParamsData();
        this.$message.success("删除成功");
      }
    },
    // 文本框失去焦点或者按下 回车键触发
    async handleInputConfirm(row) {
      console.log("ok");
      // .trim()除去空格
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }else{
        row.inputVisible = false;
        row.attr_vals.push(row.inputValue.trim())
        row.inputValue = "";
        const {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,
        {attr_name:row.attr_name,
        attr_sel:this.activeName,
        attr_vals:row.attr_vals.join(' ')})
        if(res.meta.status !== 200){
          return this.$message.error('更新失败')
        }
         return this.$message.success('更新成功')
      }
    },
    // 点击按钮切换到文本输入框
    showInput(row) {
      row.inputVisible = true;
      // 让文本框自动获得焦点
      // $nextTick 作用，当页面上元素被重新渲染后才会则行
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    async handleClose(i,row){
      row.attr_vals.splice(i,1)
      const {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,
        {attr_name:row.attr_name,
        attr_sel:this.activeName,
        attr_vals:row.attr_vals.join(' ')})
        if(res.meta.status !== 200){
          return this.$message.error('更新失败')
        }
         return this.$message.success('更新成功')
    }
  },
  computed: {
    // 如果按钮需要被禁用就返回true
    isBtnDisabled() {
      if (this.selectedCateKeys.length !== 3) {
        return true;
      }
      return false;
    },
    // 当前选中的三级分类id
    cateId() {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2];
      }
      return null;
    },
    //动态计算标题文本
    titleText() {
      if (this.activeName === "many") {
        return "动态参数";
      } else {
        return "静态属性";
      }
    },
  },
};
</script>

<style lang="less" scoped>
.span {
  margin: 5px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 100px;
}
</style>